<!DOCTYPE html>
<title>FormData interface</title>
<script src="../../../../resources/testharness.js"></script>
<script src="../../../../resources/testharnessreport.js"></script>
<script>

// Helpers

function serializeFormData(formData)
{
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest(), async = true;
        xhr.open(
            'POST',
            'http://127.0.0.1:8000/xmlhttprequest/resources/multipart-post-echo.php',
            async);
        xhr.send(formData);
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== XMLHttpRequest.DONE)
                return;
            if (xhr.status === 200) {
                resolve(xhr.responseText);
            } else {
                reject(Error(xhr.statusText));
            }
        };
    });
}

function checkFormData(test, formData, expected, message)
{
    message = message || 'Serialized FormData should match';
    return serializeFormData(formData)
        .then(test.step_func(function(value) {
            assert_equals(value, expected, message);
            test.done();
        }))
        .catch(test.unreached_func('Failed to fetch form data'));
}

function blobAsString(blob)
{
    return new Promise(function(resolve, reject) {
        var reader = new FileReader();
        reader.readAsText(blob);
        reader.onload = function(e) { resolve(reader.result); };
        reader.onerror = function(e) { reject(reader.error); };
    });
}

function checkBlobData(test, blob, expected, message)
{
    message = message || 'Blob data should match';
    return blobAsString(blob)
        .then(test.step_func(function(value) {
            assert_equals(value, expected, message);
            test.done();
        }))
        .catch(test.unreached_func('Failed to read Blob data'));
}

// Tests

async_test(function(t) {
    var fd = new FormData();
    fd.append('n1', 'value');
    assert_equals(fd.has('n1'), true,
                  'FormData.has() should see appended entry');
    assert_equals(fd.has('n2'), false,
                  'FormData.has() should not see absent entry');
    fd.append('n2', 'value');
    assert_equals(fd.has('n1'), true,
                  'FormData.has() should still see original entry');
    assert_equals(fd.has('n2'), true,
                  'FormData.has() should see newly appended entry');
    fd.append('n3', new Blob(['content']));
    assert_equals(fd.has('n3'), true,
                  'FormData.has() should see newly appended Blob entry');

    checkFormData(t, fd,
                  'n1=value&n2=value&n3=blob:application/octet-stream:content');
}, 'FormData.has()');

async_test(function(t) {
    var fd = new FormData();
    fd.append('name', 'value');
    assert_equals(fd.has('name'), true,
                  'FormData.has() should see appended entry');
    fd.delete('name');
    assert_equals(fd.has('name'), false,
                  'FormData.has() should not see deleted entry');

    fd.append('name', new Blob(['content']));
    assert_equals(fd.has('name'), true,
                  'FormData.has() should see newly appended Blob entry');
    fd.delete('name');
    assert_equals(fd.has('name'), false,
                  'FormData.has() should not see deleted Blob entry');

    fd.append('n1', 'v1');
    fd.append('n2', 'v2');
    fd.append('n1', 'v3');
    fd.delete('n1');
    assert_equals(fd.has('n1'), false,
                  'FormData.delete() should delete all matching entries');

    checkFormData(t, fd, 'n2=v2');
}, 'FormData.delete()');

async_test(function(t) {
    var fd = new FormData();
    fd.set('n1', 'v1');
    assert_equals(fd.has('n1'), true, 'FormData.has() should see set() entry');
    checkFormData(t, fd, 'n1=v1');
}, 'FormData.set() - DOMString');

async_test(function(t) {
    var fd = new FormData();
    fd.set('n1', new Blob(['content']));

    checkFormData(t, fd, 'n1=blob:application/octet-stream:content');
}, 'FormData.set() - Blob');

async_test(function(t) {
    var fd = new FormData();
    fd.set('n1', new Blob(['content']), 'name1');

    checkFormData(t, fd, 'n1=name1:application/octet-stream:content');
}, 'FormData.set() - Blob and filename');

async_test(function(t) {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n1', 'v2');
    fd.set('n1', 'v3');
    assert_equals(fd.has('n1'), true, 'FormData.has() should see set() entry');
    fd.set('n2', 'v4');
    fd.set('n2', new Blob(['content']), 'name1');

    checkFormData(t, fd, 'n1=v3&n2=name1:application/octet-stream:content',
                  'FormData.set() should replace all matching entries');
}, 'FormData.set() replaces all entries');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    var result = fd.get('n1');
    assert_equals(result, 'v1',
                  'FormData.get() should return matching DOMString entry');
}, 'FormData.get() - DOMString');

async_test(function(t) {
    var fd = new FormData();
    fd.append('n1', new Blob(['content']));
    var result = fd.get('n1');
    assert_true(result instanceof File,
                'FormData.get() on an appended Blob should return a File');
    assert_equals(result.name, 'blob', 'Default name on a Blob is "blob"');
    checkBlobData(t, result, 'content');
}, 'FormData.get() - Blob');

async_test(function(t) {
    var fd = new FormData();
    fd.append('n1', new Blob(['content']), 'name1');
    var result = fd.get('n1');
    assert_true(result instanceof File,
                'FormData.get() on an appended Blob should return a File');
    assert_equals(result.name, 'name1',
                  'Returned File should have specified name');
    checkBlobData(t, result, 'content');
}, 'FormData.get() - Blob and filename');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n1', 'v2');
    var result = fd.get('n1');
    assert_equals(result, 'v1',
                  'FormData.get() should return first matching entry');
}, 'FormData.get() - multiple matches');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n2', 'v2');
    var result = fd.get('n3');
    assert_equals(result, null,
                  'FormData.get() should return null if no matches');
}, 'FormData.get() - no matches');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n2', 'v2');
    fd.append('n1', new Blob(['content']));
    fd.append('n3', 'v3');
    fd.append('n1', new Blob(['content2']), 'name2');
    fd.append('n4', 'v4');
    var results = fd.getAll('n1');

    assert_equals(results.length, 3,
                  'FormData.getAll() should return all matching entries');

    assert_equals(results[0], 'v1', 'First entry should match');

    assert_true(results[1] instanceof File, 'Second entry should be a File');
    assert_equals(results[1].name, 'blob',
                  'Second entry name should be the default');

    assert_true(results[2] instanceof File, 'Third entry should be a File');
    assert_equals(results[2].name, 'name2',
                  'Third entry name should be as specified');
}, 'FormData.getAll()');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n2', 'v2');
    var results = fd.getAll('n3');

    assert_equals(results.length, 0,
                  'FormData.getAll() should return empty sequence if no ' +
                  'matches');
}, 'FormData.getAll() - no matches');

test(function() {
    var fd = new FormData();
    fd.set('f1', new File(['content'], 'name1'));
    fd.append('f2', new File(['content'], 'name2'));
    fd.set('f3', new File(['content'], 'name3'), 'override3');
    fd.append('f4', new File(['content'], 'name4'), 'override4');

    assert_equals(fd.get('f1').name, 'name1',
                  'Original name of set file should be used');
    assert_equals(fd.get('f2').name, 'name2',
                  'Original name of appended file should be used');
    assert_equals(fd.get('f3').name, 'override3',
                  'Overridden name of set file should be used');
    assert_equals(fd.get('f4').name, 'override4',
                  'Overridden name of appended file should be used');
}, 'FormData.get() - Files with name overrides');

test(function() {
    var fd = new FormData();
    fd.set('f1', new File(['content'], 'name1'));
    fd.append('f1', new File(['content'], 'name2'));
    fd.set('f2', new File(['content'], 'name3'), 'override3');
    fd.append('f2', new File(['content'], 'name4'), 'override4');

    var results1 = fd.getAll('f1');
    var results2 = fd.getAll('f2');
    assert_equals(results1[0].name, 'name1',
                  'Original name of set file should be used');
    assert_equals(results1[1].name, 'name2',
                  'Original name of appended file should be used');
    assert_equals(results2[0].name, 'override3',
                  'Overridden name of set file should be used');
    assert_equals(results2[1].name, 'override4',
                  'Overridden name of appended file should be used');
}, 'FormData.getAll() - Files with name overrides');

test(function() {
    var file = new File(['content'], 'name');
    var blob = new Blob(['content']);

    var now = Date.now();
    var fd = new FormData();
    fd.set('file1', file);
    fd.set('file2', file, 'override');
    fd.set('blob1', blob);
    fd.set('blob2', blob, 'override');

    assert_equals(Number(fd.get('file1').lastModifiedDate),
                  Number(file.lastModifiedDate),
                  'timestamp of file should be preserved');

    assert_equals(Number(fd.get('file2').lastModifiedDate),
                  Number(file.lastModifiedDate),
                  'timestamp of file with name override should be preserved');

    // NTP resets, different clocks (between DOM and JS), and just
    // slow machines (due to test loads) can make timestamp samples
    // vary between samples, so allow for some imprecision. We're
    // really just ensuring it's "nowish"; not the Epoch and not
    // initialized with the wrong units (s vs. ms).

    var epsilon_ms = 60 * 1000; // 60s - close enough.

    assert_approx_equals(Number(fd.get('blob1').lastModifiedDate),
                         now,
                         epsilon_ms,
                         'timestamp of blob should be nowish');
    assert_approx_equals(Number(fd.get('blob2').lastModifiedDate),
                         now,
                         epsilon_ms,
                         'timestamp of blob should be nowish');
}, 'FormData - lastModifiedDate of File/Blob entries');

async_test(function(t) {
    var sample =
        '\xC0' + // 'LATIN CAPITAL LETTER A WITH GRAVE' (U+00C0)
        '\xC1' + // 'LATIN CAPITAL LETTER A WITH ACUTE' (U+00C1)
        '\xE0' + // 'LATIN SMALL LETTER A WITH GRAVE' (U+00E0)
        '\xE1' + // 'LATIN SMALL LETTER A WITH ACUTE' (U+00E1)
        '\xFF' + // 'LATIN SMALL LETTER Y WITH DIAERESIS' (U+00FF)
        '\u0100' + // 'LATIN CAPITAL LETTER A WITH MACRON' (U+0100)
        '\u1000' + // 'MYANMAR LETTER KA' (U+1000)
        '\uD834\uDD1E' + // 'MUSICAL SYMBOL G-CLEF' (U+1D11E) - UTF-16 surrogate pairs
        '\uFFFD'; // 'REPLACEMENT CHARACTER' (U+FFFD)

    var fd = new FormData();
    fd.append('k1' + sample, 'v1' + sample);
    fd.set('k2' + sample, 'v2' + sample);
    assert_equals(fd.get('k1' + sample), 'v1' + sample,
                  'Set entry should encode/decode correctly');
    assert_equals(fd.get('k2' + sample), 'v2' + sample,
                  'Appended entry should encode/decode correctly');
    checkFormData(t, fd,
                  'k1' + sample + '=v1' + sample + '&' +
                  'k2' + sample + '=v2' + sample);
}, 'FormData - encoding round-trip');

test(function() {
    var fd = new FormData();
    fd.append('k1\uD800', 'v1\uDC00');
    assert_equals(fd.get('k1\uFFFD'), 'v1\uFFFD',
                         'Invalid UTF-16 in append() should yield U+FFFD');
    fd.set('k2\uD800', 'v2\uDC00');
    assert_true(fd.has('k2\uFFFD'),
                       'Invalid UTF-16 in set() should yield U+FFFD');
    assert_true(fd.has('k2\uD800'),
                       'Invalid UTF-16 in has() should yield U+FFFD');
    assert_equals(fd.get('k2\uD800'), 'v2\uFFFD',
                         'Invalid UTF-16 in get() should yield U+FFFD');
    fd.delete('k2\uD800');
    assert_false(fd.has('k2\uD800'),
                       'Invalid UTF-16 in delete() should yield U+FFFD');
}, 'FormData - ScalarValueStrings');

test(function() {
    var fd = new FormData();
    fd.append('n1', 'v1');
    fd.append('n2', 'v2');
    fd.append('n3', 'v3');
    fd.append('n1', 'v4');
    fd.append('n2', 'v5');
    fd.append('n3', 'v6');
    fd.delete('n2');

    var expected_keys = ['n1', 'n3', 'n1', 'n3'];
    var expected_values = ['v1', 'v3', 'v4', 'v6'];

    (function() {
        var keys = [], values = [];
        for(var entry of fd) {
            assert_equals(entry.length, 2,
                          'Default iterator should yield key/value pairs');
            keys.push(entry[0]);
            values.push(entry[1]);
        }
        assert_array_equals(keys, expected_keys,
                            'Default iterator should see duplicate keys');
        assert_array_equals(values, expected_values,
                            'Default iterator should see non-deleted values');
    }());

    (function() {
        var keys = [], values = [];
        for(var entry of fd.entries()) {
            assert_equals(entry.length, 2,
                          'entries() iterator should yield key/value pairs');
            keys.push(entry[0]);
            values.push(entry[1]);
        }
        assert_array_equals(keys, expected_keys,
                            'entries() iterator should see duplicate keys');
        assert_array_equals(values, expected_values,
                            'entries() iterator should see non-deleted values');
    }());

    (function() {
        var keys = [];
        for(var entry of fd.keys())
            keys.push(entry);
        assert_array_equals(keys, expected_keys,
                            'keys() iterator should see duplicate keys');
    }());

    (function() {
        var values = [];
        for(var entry of fd.values())
            values.push(entry);
        assert_array_equals(values, expected_values,
                            'values() iterator should see non-deleted values');
    }());

}, 'FormData - iterators');

test(function() {
    var gen_different_crlf_keys = function(val) {
        if (val.indexOf('\r\n') !== -1) {
            return [val.replace('\r\n', '\r'), val.replace('\r\n', '\n')];
        } else if (val.indexOf('\r') !== -1) {
            return [val.replace('\r', '\n'), val.replace('\r', '\r\n')];
        } else {
            return [val.replace('\n', '\r'), val.replace('\n', '\r\n')];
        }
    }

    var fd = new FormData();
    fd.set('key\r1', 'value\r1');
    fd.append('key\n2', 'value\n2');
    fd.append('key\r\n3', 'value\r\n3');

    var expected_keys = ['key\r1', 'key\n2', 'key\r\n3'];
    var expected_values = ['value\r1', 'value\n2', 'value\r\n3'];

    for (var i = 0; i < expected_keys.length; ++i) {
        var expected_key = expected_keys[i];
        var expected_value = expected_values[i];

        assert_true(fd.has(expected_key),
                    'has() should return true when tested with expected key');
        assert_equals(fd.get(expected_key), expected_value,
                    'get() should return the expected value');
        var val_arr = fd.getAll(expected_key);
        assert_true(val_arr.length === 1 && val_arr[0] === expected_value,
                    'getAll() should return the expected value');

        var wrong_keys = gen_different_crlf_keys(expected_key);

        for (var j = 0; j < wrong_keys.length; ++j) {
            var wrong_key = wrong_keys[j];
            assert_false(fd.has(wrong_key),
                         'has() should return false with keys in other CRLF form');
            assert_equals(fd.get(wrong_key), null,
                          'get() should return null with keys in other CRLF form');
            assert_equals(fd.getAll(wrong_key).length, 0,
                'getAll() should return empty array with keys in other CRLF form');
        }
    }

    var count_keys = function(keys) {
        var counter = 0;
        for (var key of keys) {
            ++counter;
        }
        return counter;
    };

    var fd = new FormData();
    fd.set('test\rkey', 'value');
    fd.append('test\nkey', 'value');
    fd.append('test\r\nkey', 'value');

    assert_equals(count_keys(fd.keys()), 3,
        'Same key in different CRLF form should be treated as different keys');

    fd.delete('test\rkey');
    assert_equals(count_keys(fd.keys()), 2,
                'delete() should only remove same CRLF form key from entries');

    fd.delete('test\nkey');
    assert_equals(count_keys(fd.keys()), 1,
                'delete() should only remove same CRLF form key from entries');

    fd.delete('test\r\nkey');
    assert_equals(count_keys(fd.keys()), 0,
                'delete() should only remove same CRLF form key from entries');

}, 'FormData - no CRLF normalization');

</script>
